#!/usr/bin/env bash

# Place a template xinitrc in ~/.xinitrc based on the system one without
# default exec lines (twm, xterm etc.) This solves the problem for new users
# who don't know how to base their ~/.xinitrc on /etc/X11/xinit/xinitrc. It
# should make it easier for them use the template from the system file.
# Written by Adnan Shameem; License: MIT (Expat)
#
# Usage:
#   - Make sure you have xorg, xinit installed on your system
#	- Optional, replace your desired exec command on the last echo statement of this script
#   - Run: ./autoxinitrc.sh

# Automatically remove default exec lines from system xinitrc and put it on ~.
# Add your custom lines afterwards to the destination file.
# Params:
#   - $1: Source filename (default: /etc/X11/xinit/xinitrc) (optional)
#   - $2: Destination filename (default: $HOME/.xinitrc) (optional)
function autoxinitrc() {
	# Default vars
	[ -z "$1" ] && local filename=/etc/X11/xinit/xinitrc || local filename="$1"
	[ -z "$2" ] && local destfile="$HOME/.xinitrc" || local destfile="$2"
	# To store sed expression for line deletion
	local exp=''
	# Line on which last paragraph started
	local para_start=1
	# Is last line blank
	local last_blank=1
	# Does paragraph has 'exec ' line
	local para_has_exec=0

	# Read file into array
	readarray -t lines < "$filename"
	for i in $(seq 1 "${#lines[@]}")
	do
		# Stores the current line contents
		line="${lines[$i]}"
		# Reached paragraph end
		if [ -z "$line" ]; then
			last_blank=1
			if [ "$para_has_exec" = "1" ]; then
				exp+="${para_start},${i}d;"
			fi
			para_has_exec=0 # reset exec search for paragraph
		# Inside a paragraph, encountered a non-empty line
		elif [ ! -z "$line" ]; then
			if [ "$last_blank" = "1" ]; then # first line of paragraph
				para_start=$i
				para_has_exec=0
				last_blank=0
			fi
			if echo "$line" | grep -e 'exec\s' &>/dev/null; then
				para_has_exec=1
			fi
		fi
	done
	if [ -f "$HOME/.xinitrc" ]; then
		mv "$HOME/.xinitrc" "$HOME/.xinitrc.bak"
	fi
	cp "$filename" "$destfile"
	sed -i'' -e "$exp" "$destfile"
}

# We're eager to replace the ~/.xinitrc
confirm=1
# When there is already a ~/.xinitrc file, ask if user wants to replace it
if [ -f "$HOME/.xinitrc" ]; then
	echo -n "There is already an existing ~/.xinitrc. Do you want to replace it [y/N]? "
	read sure_input
	if [[ ! "$sure_input" =~ ^([yY][eE][sS]|[yY])$ ]]; then
		confirm=0
	fi
fi
if [ "$confirm" = "1" ]; then
	# Place a template xinitrc in ~/.xinitrc without default exec lines
	autoxinitrc
	# Actual exec commands we want when 'startx' is run
	echo "
# Run openbox
exec openbox-session
" >> "$HOME/.xinitrc"
fi
